<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\CouponList;
use app\common\model\MoneyLog;
use app\common\model\RechargeLog;
use app\common\model\RechargeOrder;
use app\common\model\User;
use app\common\model\Order;
use app\common\model\UserCoupon;
use fast\Random;
use think\Db;
use think\Validate;
require_once "wxpay/lib/WxPay.Api.php";
require_once "wxpay/example/WxPay.Config.php";
require_once "wxpay/example/WxPay.JsApiPay.php";

class Response extends Api
{

    public function goods_response (){
        $data    = file_get_contents('php://input');
        $data = $this->xml_to_data($data);
        // sign不参与签名算法
        $data_sign = $data['sign'];
        unset($data['sign']);
        $sign = $this->makeSign($data);
        /* $sign = 1;
         $data_sign = 1;
         $data = [
             'return_code'=>'SUCCESS',
             'result_code'=>'SUCCESS',
             'out_trade_no'=>'J9156288943356',
         ];*/
        // 判断签名是否正确 判断支付状态
        if (($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
            $goods_order = Order::where('order_sn',$data['out_trade_no'])->find();
            if($goods_order && $goods_order['status'] ==0){
                //更改订单状态
                Db::startTrans();
                $res = Order::where('order_sn',$data['out_trade_no'])->update(['status'=>1,'paytime'=>time()]);
                if($res){
                    //2.如果使用优惠券的话，改变优惠券状态
                    if($goods_order['coupon_id']){
                        $coupon_info = UserCoupon::where(['userid'=>$goods_order['userid'],'status'=>0,'id'=>$goods_order['coupon_id']])->find();
                        if($coupon_info){
                            $res1 = UserCoupon::where(['userid'=>$goods_order['userid'],'status'=>0,'id'=>$goods_order['coupon_id']])->update(['status'=>1]);
                        }
                    }
                }
                Db::commit();
                if($res && $res1){
                    return 'SUCCESS';
                }
            }
        }else{
            return 'FALL';
        }
    }
    //充值余额回调
    public function recharge_response (){
       /* $data    = file_get_contents('php://input');
        $data = $this->xml_to_data($data);
        // sign不参与签名算法
        $data_sign = $data['sign'];
        unset($data['sign']);
        $sign = $this->makeSign($data);*/
         $sign = 1;
         $data_sign = 1;
         $data = [
             'return_code'=>'SUCCESS',
             'result_code'=>'SUCCESS',
             'out_trade_no'=>'REJC018988505195',
         ];
        // 判断签名是否正确 判断支付状态
        if (($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
            $goods_order = RechargeOrder::where('order_sn',$data['out_trade_no'])->find();
            if($goods_order && $goods_order['status'] ==0){
                //更改订单状态
                Db::startTrans();
                $res = RechargeOrder::where('order_sn',$data['out_trade_no'])->update(['status'=>1,'paytime'=>time()]);
                if($res){
                    //给用户添加余额记录和余额
                    $data = [
                        'userid'=>$goods_order['userid'],
                        'money'=>$goods_order['money']+$goods_order['give_money'],
                        'status'=>1,
                    ];
                    $res1 = MoneyLog::create($data);
                    if($res1){
                        $res2 = User::where('id',$data['userid'])->setInc('money',$data['money']);
                    }
                    //查看有没有充值对应的优惠券，如果有的话，发放给用户
                    $coupon = RechargeLog::where('id',$goods_order['recharge_id'])->find();
                    if($coupon){
                        $coupon_list = CouponList::where('id','in',$coupon['coupon_ids'])->select();
                        foreach($coupon_list as &$value){
                            $datas['userid'] = $goods_order['userid'];
                            $datas['image'] = $value['image'];
                            $datas['name'] = $value['name'];
                            $datas['type'] = $value['status'];
                            $datas['discount'] = $value['discount'];
                            $datas['expiredtime'] = $value['expiredtime'];
                            $res3 = UserCoupon::create($datas);
                        }
                    }else{
                        $res3= true;
                    }
                }
                Db::commit();
                if($res && $res1 && $res2 && $res3){
                    return 'SUCCESS';
                }
            }
        }else{
            return 'FALL';
        }
    }
    public function xml_to_data($xml){
        if(!$xml){
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }
    /**
     * 接收通知成功后应答输出XML数据
     * @param string $xml
     */
    public function replyNotify(){
        $data['return_code'] = 'SUCCESS';
        $data['return_msg'] = 'OK';
        $xml = $this->data_to_xml( $data );
        echo $xml;
        die();
    }

    function data_to_xml($arr){
        $xml = "<root>";
        foreach ($arr as $key=>$val){
            if(is_array($val)){
                $xml.="<".$key.">".data_to_xml($val)."</".$key.">";
            }else{
                $xml.="<".$key.">".$val."</".$key.">";
            }
        }
        $xml.="</root>";
        return $xml;
    }

    /**

     * 生成签名

     * @return 签名，本函数不覆盖sign成员变量

     */
    protected function makeSign($data){
        //获取微信支付秘钥
        //require_once "wxpay/lib/WxPay.Api.php";
        $key = 'gtTbEWhSWLE88AeTZZnFJuTbMBPSWguE';
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp=$string_a."&key=".$key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }
    public function wx_pay($order_number,$price,$openid,$notify_url){
        // vendor('Qiniu.autoload');

        $tools = new \JsApiPay();
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("订单信息");
        $input->SetAttach("test");
        $input->SetOut_trade_no($order_number);//订单号
        $input->SetTotal_fee($price*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $config = new \WxPayConfig();
        $order = \WxPayApi::unifiedOrder($config, $input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //print_r($order);exit;
        $jsApiParameters = $tools->GetJsApiParameters($order);
        return $jsApiParameters;
    }
}
